#include "Controler.h"


Controler::Controler(void)
{
	pipe = NULL;
	ZeroMemory(buffer, BUFSIZE);
	connected = false;
}


Controler::~Controler(void)
{
	if(connected && pipe != NULL)
		CloseHandle(pipe);
}


int Controler::openConnection(){
	DWORD mode = PIPE_READMODE_MESSAGE;
	while(1){
		pipe = CreateFile(PIPE_NAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
		if(pipe != INVALID_HANDLE_VALUE)
			break;
		if(GetLastError() != ERROR_PIPE_BUSY)
			return 1;
		if(!WaitNamedPipe(PIPE_NAME, 15000))
			return 2;
	}
	connected = true;
	if(SetNamedPipeHandleState(pipe, &mode, NULL, NULL))
		return 3;
	return 0;
}


int Controler::closeConnection(){
	if(connected && pipe != NULL){
		CloseHandle(pipe);
		connected = false;
		return 0;
	}
	return 1;
}


int Controler::sendMessage(char *msg, PDWORD length){
	DWORD control;
	if(!connected || pipe == NULL || pipe == INVALID_HANDLE_VALUE)
		return 1;
	WriteFile(pipe, msg, length==0?strlen(msg):*length, length==0?&control:length, NULL);
	return length==0?control:*length;
}


char* Controler::receiveMessage(){
	char *result, *buffer, *rBuff;
	DWORD read;
	int count = 0;
	rBuff = (char*)calloc(1, BUFSIZE);
	result = 0;
	while(!ReadFile(pipe, rBuff, BUFSIZE, &read, NULL) && GetLastError() == ERROR_MORE_DATA){
		buffer = result;
		count++;
		result = (char*)malloc(count*BUFSIZE+1);
		ZeroMemory(result, count*BUFSIZE+1);
		if(buffer != 0){
			memcpy(result, buffer, (count-1)*BUFSIZE);
			free(buffer);
		}
		strcpy_s(result, count*BUFSIZE+1, rBuff);
		ZeroMemory(rBuff, BUFSIZE);
	}
	buffer = result;
	count++;
	result = (char*)malloc(count*BUFSIZE+1);
	if(buffer != 0){
		memcpy(result, buffer, (count-1)*BUFSIZE);
		free(buffer);
	}
	strcpy_s(result, count*BUFSIZE+1, rBuff);
	free(rBuff);
	return result;
}